﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using System.Text;
using Telerik.Web.UI;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class AdjustBudgetUnit : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        private void SalesbillImportstatus(string company, string sYear, string sMonth)
        {
            BudgetBll bll = new BudgetBll();

            if (ddlCompany.SelectedValue != "")
            {
                if (bll.BillSaleAdjustStatus(sYear, sMonth, company) == 1)
                {
                    msg.Text = "已关账！";
                    Button4.Enabled = false;
                    hidMsg.Value = "1";
                }
                else
                {
                    msg.Text = "";
                    hidMsg.Value = "0";
                    Button4.Enabled = true;
                }

            }
            else
            {
                Button4.Enabled = false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", ""));
                
                SalesbillImportstatus(this.ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
                if (ddlCompany.SelectedValue != null && ddlCompany.SelectedValue != "")
                {
                    BudgetBll bll = new BudgetBll();
                    string UnlockYearmonth = bll.GetunSaleLockMonth(ddlCompany.SelectedValue);
                    ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
                }
                if (ddlCompany.SelectedValue != "")
                {
                    SalebillAdjuststatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
                }
                BindGrid(1);
                Calculate();

                LoadRadTree("");

                BindGrid1(1);
                Calculate1();

            }
        }

        private void SalebillAdjuststatus(string company, string sYear, string sMonth)
        {
            BudgetBll bll = new BudgetBll();
            if (bll.BillSaleAdjustStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "已关账！";
                hidMsg.Value = "1";
                Button4.Enabled = false;
            }
            else
            {
                msg.Text = "";
                hidMsg.Value = "0";
                Button4.Enabled = true;
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SalesbillImportstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
            BindGrid1(1);
            Calculate1();
            
        }

        protected void Button4_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company == "")
            {
                msg.Text = "请选择开票公司。";
                return;
            }

            if (bll.BillSaleAdjustStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "选择月份的销售数据调整已关闭。";
                return;
            }

            bll.setSaleDataAdjustStatus(sYear, sMonth, company, "1", base.CurrentUserEntity.UserName, DateTime.Now);
            msg.Text = "成功关闭销售数据调整。";
        }

        protected void gridAccessoryList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "associate")
            {
                string rowinfoex = "";
                rowinfoex = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["rowInfoex"].ToString();
                string[] sArray_budget;

                sArray_budget = rowinfoex.Split('|');
                string budgetcompanyname = sArray_budget[0];
                string budgetcustomercode = sArray_budget[1];
                string budgetcategorycode = sArray_budget[2];
                string budgetsales = sArray_budget[3];

                string Inssql = "";
                BillBll bll = new BillBll();

                foreach (Telerik.WebControls.GridItem item in gridAccessoryList.Items)
                {
                    if (item.ItemType == Telerik.WebControls.GridItemType.Item || item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
                    {
                        string rowinfo = item.OwnerTableView.DataKeyValues[item.ItemIndex]["rowInfo"].ToString();
                        string[] sArray;
                        string userName = base.CurrentUserEntity.UserName;
                        CheckBox chkSel = item.FindControl("chkSel") as CheckBox;
                        if (chkSel.Checked && rowinfo!="")
                        {
                            sArray = rowinfo.Split('|');
                            string billunit = sArray[0];
                            string cCusCode = sArray[1];
                            string cCategoryCode = sArray[2];

                            if (budgetcategorycode != cCategoryCode)
                            { ClientScript.RegisterStartupScript(this.GetType(), "关联提示！", "alert('预算的产品分类必须和销售的产品分类一致！');", true); return; }
                            Inssql += @"insert into BudgetUnitRef(BillUnit,CustomerCode,categoryCode,BudgetUnit,BudgetCustomerCode,BudgetCategoryCode,Sales,OperatorName) values('" + billunit + "','" + cCusCode + "','" + cCategoryCode + "','" + budgetcompanyname + "','" + budgetcustomercode + "','" + budgetcategorycode + "','" + budgetsales + "','" + userName + "');";
                        }
                    }
                }
                if (Inssql == "") { ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请选择需要关联的数据。');", true); return; }
                int rnt = bll.Executesql(Inssql);

                if (rnt > 0)
                {

                    ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('关联成功。');", true);
                }
            }
            
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
            Response.Redirect("AdjustBudgetUnit.aspx");
        }
        
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindGrid1(AspNetPager2.CurrentPageIndex);
            Calculate1();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        private void LoadRadTree(string categoryCode)
        {
            string categoryGUID = "";
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            dt = bll.GetInstrumentCategory("");//  and SUBSTRING(categorycode,1,2) in('01', '02')


            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryCode != "")
            {
                Text1.Value = categoryCode;
                List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode");

                if (categoryEntitys != null && categoryEntitys.Count > 0)
                {
                    categoryGUID = categoryEntitys[0].categoryCode;
                }

                if (categoryGUID != "")
                {
                    txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                    RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                }
            }

        }

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().SaleBillNotinBudget(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
            AspNetPager1.RecordCount = RecordCount;
        }

        private void BindGrid1(int pageindex)
        {
            string sb = getWhereClause1();

            int RecordCount = 0;
            DataTable dt = new BillBll().BudgetNotSaleBill(sb, SortString, AspNetPager2.PageSize, pageindex, out RecordCount);

            AspNetPager2.RecordCount = RecordCount;
            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
            AspNetPager2.RecordCount = RecordCount;
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BillBll bll = new BillBll();
            DataTable dt = bll.CalcbillAmount(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotalSale.Text = "合计销售总额：" + string.Format("{0:N}", dt.Rows[0]["iNatSum"]);
            }
            else
            {

                lblTotalSale.Text = "";
            }
        }

        private void Calculate1()
        {

            string sb = getWhereClause1();
            
            BillBll bll = new BillBll();
            DataTable dt = bll.CalcBudgetAmount(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotalBudget.Text = "合计预算总额：" + string.Format("{0:N}", dt.Rows[0]["TotalAmount"]);
            }
            else
            {

                lblTotalSale.Text = "";
            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
            

        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

            string beginDT, endDT;

            beginDT = ddlBudgetYear.SelectedValue + "-" + ddlBudgetMonth.SelectedValue + "-01";
            endDT = DataValid.Monthlastday(ddlBudgetYear.SelectedValue + "-" + ddlBudgetMonth.SelectedValue + "-01");

            //sb.Append(" and a.[dDate]  between '").Append(beginDT + "' and '").Append(endDT + "'");
            sb.Append(" and a.[dDate] <= '").Append(endDT + "'");

            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and a.BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and a.cCusCode in(").Append("select CustomerCode from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }

            //sb.Append(" and (a.companyname in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            //sb.Append(" or a.cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where PM='").Append(base.CurrentUserEntity.UserName.ToString()).Append("'))");

            sb.Append(" and (a.companyname in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            sb.Append(" and a.CategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");

            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and a.companyname = '" + ddlCompany.SelectedValue.ToString() + "'");
            }
            sb.Append(" and a.cCategoryCode != '010104' and left(a.cCategoryCode,2) in('01','02')");
            

            return sb.ToString();
        }

        private string getWhereClause1()
        {
            StringBuilder sb = new StringBuilder();

            string categoryCode = "";
            string customerCode = "";

            //if (base.CurrentUserEntity.UserName == "郭海涛"
            //    || base.CurrentUserEntity.UserName == "史莹"
            //    || base.CurrentUserEntity.UserName == "王静"
            //    || base.CurrentUserEntity.UserName == "顾悦"
            //    || base.CurrentUserEntity.UserName == "宋欣"
            //    || base.CurrentUserEntity.UserName == "徐雪峰"
            //    || base.CurrentUserEntity.UserName == "胡日成"
            //    || base.CurrentUserEntity.UserName == "崔丽丽"
            //    || base.CurrentUserEntity.UserName == "官俊"
            //    || base.CurrentUserEntity.UserName == "李娜"
            //    || base.CurrentUserEntity.UserName == "张佳锦"
            //    || base.CurrentUserEntity.UserName == "系统管理员"
            //    )
            //{
            //    sb.Append(" and v.companyname in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            //}
            //else
            //{
             //   sb.Append(" and (v.companyname in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
             //   sb.Append(" or v.CategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where PM='").Append(base.CurrentUserEntity.UserName.ToString()).Append("'))");
             //}
            sb.Append(" and (v.companyname in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            sb.Append(" and v.CategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and v.companyname = '" + ddlCompany.SelectedValue.ToString() + "'");
            }

            SystemBll bll = new SystemBll();

            if (Text1.Value != "")
            {
                Guid ID = new Guid(Text1.Value);
                CtrtInstrumentCategoryEntity instrmentEntity = bll.Get<CtrtInstrumentCategoryEntity>(ID);
                if (instrmentEntity != null)
                {
                    categoryCode = instrmentEntity.categoryCode;
                }
            }

            if (hidCustomerID.Value != "")
            {
                customerCode = bll.Get<CtrtCustomerEntity>(new Guid(hidCustomerID.Value)).CustomerCode;
            }

            if (categoryCode != "") { sb.Append(" and v.categorycode like '").Append(categoryCode).Append("%'"); }
            if (customerCode != "") { sb.Append(" and v.customerCode = '").Append(customerCode).Append("'"); }
            if (txtSales.Text.Trim() != "") { sb.Append(" and v.sales = '").Append(txtSales.Text.Trim()).Append("'"); }

            return sb.ToString();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BudgetBll bll = new BudgetBll();

            DataTable dt = bll.ExportSalesBudgets(Whereclause, " [客户] asc ");

            Export.Export2Excel(dt, "销售预算一览表", Page.Response);

        }

        
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindGrid1(1);
        }

        protected void RadGrid1_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
                string strsql;
                string associatestrEx;
                int associateSum;
                    
                if (dv != null)
                {
                    LinkButton lnkbtnAssociate = e.Item.FindControl("lnkbtnAssociate") as LinkButton;
                    LinkButton lnkbtnCancelAssociate = e.Item.FindControl("lnkbtnCancelAssociate") as LinkButton;
                    //if (dv["CategoryName"].ToString().Contains("折扣"))
                    
                   strsql = " and Budgetcustomercode = '" + dv["customercode"].ToString() + "' and Budgetcategorycode='" + dv["categorycode"].ToString() + "' and sales='" + dv["sales"].ToString() + "' and BudgetUnit='" + dv["companyname"].ToString() + "'";
                   
                    associateSum = new BillBll().AssociatedSaleUnitnum(strsql);
                    if (associateSum > 0)
                    { 
                        associatestrEx = "关联(" + associateSum.ToString() + ")";
                        lnkbtnCancelAssociate.Visible = true;
                        //lnkbtnCancelAssociate.NavigateUrl = "CancelAssociate.aspx?condition=" + strsql;
                        lnkbtnCancelAssociate.OnClientClick = JsExtension.CreateModalWindowScript("CancelAssociate.aspx?Budgetcustomercode=" + dv["customercode"].ToString() + "&Budgetcategorycode=" + dv["categorycode"].ToString() + "&sales=" + Server.UrlEncode(dv["sales"].ToString()) + "&BudgetUnit=" + Server.UrlEncode(dv["companyname"].ToString()), "", 800, 300);
                    }
                    else { 
                        associatestrEx = "关联";
                        lnkbtnCancelAssociate.Visible = false;
                    }
                    lnkbtnAssociate.Text = associatestrEx;
                }
            }

        }

        

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
              
                if (dv != null)
                {
                    CheckBox chkSel = e.Item.FindControl("chkSel") as CheckBox;
                    LinkButton lnkbtnCancelAssociate = e.Item.FindControl("lnkbtnCancelAssociate") as LinkButton;
                    if (hidMsg.Value=="1")
                    {
                        chkSel.Visible = false;
                    }
                    else
                    {
                        chkSel.Visible = true;
                    }
                }
            }
        }

        protected void ddlBudgetMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                SalebillAdjuststatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }
        }

        protected void ddlBudgetYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                SalebillAdjuststatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                SalebillAdjuststatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }
        }


        protected void btnExport_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" and (a.BillUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            sb.Append(" and a.categoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");

            string Whereclause = sb.ToString();

            BillBll bll = new BillBll();

            DataTable dt = bll.GetAssociatedBudgetList_export(Whereclause);

            Export.Export2Excel(dt, "销售关联预算一览表", Page.Response);
        }

    }
}
